<!DOCTYPE html>
    <html lang="en">
        <head>
        <meta charset="UTF-8"  name="viewport" content="width=device-width,initial-scale=1.0" />
        <title>成都骡马市站基坑监测平台</title>
        <!-- 引入SheetJS和Highcharts库 -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.1/xlsx.full.min.js"></script>
        <script src="https://code.highcharts.com/highcharts.js"></script>
        <script src="https://code.highcharts.com/modules/exporting.js"></script>
        <script src="https://code.highcharts.com/modules/export-data.js"></script>
        <!-- 引用jQuery库 -->
        <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
  
        <link rel="stylesheet" href="https://cloud.dev.pkpm.cn/bimviewer/viewer/v5/obv.css" type="text/css" />
        <link rel="resource" type="application/l10n" href="https://cloud.dev.pkpm.cn/bimviewer/viewer/v5/locale/locale.properties">
        <script src="https://cloud.dev.pkpm.cn/bimviewer/viewer/v5/obv.js"></script>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/uikit@3.5.5/dist/css/uikit.min.css" />
        <script src="https://lib.baomitu.com/echarts/4.7.0/echarts-en.min.js"></script>
        <style>
            
            @media (max-width: 760px) {
              .my-obv-domContainer {
                top: 110px !important;
                right: 0 !important;
                /*display: block !important;*/
              }
              .my-obv-domContainer button {
                font-size: 12px;
                padding: 0 10px;
              }
            }
            html, body {
              width: 100%;
              height: 100%;
              margin: 0px;
              padding: 0px;
              background: #3c3f41;
            }
            .my-obv-viewer {
              position: relative;
              width: 100%;
              height: 100%;
              display: inline-block;
            }
            .my-obv-domContainer {
              position: absolute;
              z-index: 99;
              top: 160px;
              right: 8px;
              display: flex;
              flex-wrap: wrap-reverse;
              flex-direction: column;
            }
            .my-obv-domContainer button {
              border-radius: 30px;
              margin-top: 20px;
              margin-right: 20px;
              float: right;
            }
            .marker-annotation{
                max-width: 400px !important;
            }
            .table-container {
                display: none;
                margin-top: 20px;
            }

            table {
                border-collapse: collapse;
                background-color: aliceblue;
            }

            th, td {
                border: 1px solid black;
                padding: 5px;
            }
            /* 鼠标移动效果 */
            td:hover {
                background-color: rgb(240, 167, 167);
                color: rgb(253, 253, 253);
            }

            /* 点击效果 */
            td.clicked {
                background-color: rgb(0, 3, 0);
                color: rgb(255, 255, 255);
            }
            #pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            margin-top: 5px;
            }
            
            #pagination div {
                padding: 10px;
                margin: 0 10px;
                /* background-color: #f0f0f0; */
                cursor: pointer;
                font-size: 14px;
            }
            
            #pagination div:hover {
                background-color: #ccc;
            }
            
        </style>
        </head>
        <body>
            <!-- 这里插件读取xlsx文件容器 -->
            <!-- urn:bimbox.object:test_bucket/all_dtata_xlsx -->
            <!-- <input type="file" id="input-file" onchange="loadFile()">    -->

            <div id="viewer" class="my-obv-viewer">
                <!-- <div id="chart-container" class="my-chart-container"></div> -->

            </div>
                <div id="domContainer" class="my-obv-domContainer">
                <button id="addMarkerComponentOne" class="uk-button uk-button-primary" >显示监测点位</button>
                <button id="clearMarkerComponentOne" class="uk-button uk-button-primary">移除监测点位</button>
                <div class="button-array">
                    <!-- 用与生成列表 -->
                    <div id="table-container" class="table-container">
                        <table>
                            <!-- <thead>
                                <tr>
                                    <th>列1</th>
                                    <th>列2</th>
                                    <th>列3</th>
                                </tr>
                            </thead> -->
                            <thead>
                                <tr>
                                    <th colspan="3">点位列表</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td >{{ data[0] }}</td>
                                    <td>{{ data[1] }}</td>
                                    <td>{{ data[2] }}</td>
                                </tr>
                                <tr>
                                    <td>{{ data[3] }}</td>
                                    <td>{{ data[4] }}</td>
                                    <td>{{ data[5] }}</td>
                                </tr>
                                <tr>
                                    <td>{{ data[6] }}</td>
                                    <td>{{ data[7] }}</td>
                                    <td>{{ data[8] }}</td>
                                </tr>
                            </tbody>
                            
                        </table>
                        <!-- 分页控件 -->
                        <div id="pagination">
                            <div onclick="previousPage()">上一页</div>
                            <div onclick="nextPage()">下一页</div>
                        </div>
                    </div>
                </div>
            </div>
            
            
            <script >
        // var currentPage = 1;  // 当前页码
        
        // // 上一页按钮点击事件
        // function previousPage() {
        //     if (currentPage > 1) {
        //         currentPage--;
        //         fetchData();
        //     }
        // }
        
        // // 下一页按钮点击事件
        // function nextPage() {
        //     currentPage++;
        //     fetchData();
        // }
        
        // // 获取数据并更新页面
        // function fetchData() {
        //     // 发送异步请求到后端，传递当前页码
        //     var xhr = new XMLHttpRequest();
        //     xhr.open("GET", "/api/data?page=" + currentPage, true);
        //     xhr.onreadystatechange = function() {
        //         if (xhr.readyState === 4 && xhr.status === 200) {
        //             var response = JSON.parse(xhr.responseText);
        //             var resultDiv = document.getElementById("result");
        //             resultDiv.innerHTML = "";  // 清空之前的结果
                    
        //             // 处理查询结果
        //             for (var i = 0; i < response.length; i++) {
        //                 var item = response[i];
        //                 var row = document.createElement("div");
        //                 row.textContent = item;
        //                 resultDiv.appendChild(row);
        //             }
        //         }
        //     };
        //     xhr.send();
        // }
        
        // // 页面加载完成后，获取第一页数据
        // window.onload = function() {
        //     fetchData();
        // };

document.getElementById('addMarkerComponentOne').onclick = function() {
    console.log(`打印标记点:'DM35-2':1245,'DM35-3':1238,'DM36-2':1239,'DM36-3':1244,'DM37-2':1243,'DM37-3':1242,'DM38-2':1243`);
    // 
    // create_table();
    var tableContainer = document.querySelector('.table-container');
    console.log(tableContainer.style.display)
    if(tableContainer.style.display === 'none' || tableContainer.style.display == '' ){
        tableContainer.style.display = 'block';
    }else{
        tableContainer.style.display = 'none';
    }
};


// 创建列表
function create_table(){
    // 创建表格元素
    var table = document.createElement("table");

    // 创建 thead 元素并添加子元素
    var thead = document.createElement("thead");
    var theadRow = document.createElement("tr");
    var theadCell = document.createElement("th");
    theadCell.setAttribute("colspan", "3");
    theadCell.textContent = "点位列表";
    theadRow.appendChild(theadCell);
    thead.appendChild(theadRow);

    // 创建 tbody 元素并添加子元素
    var tbody = document.createElement("tbody");
    var data = ["DM35-2", "DM35-3", "DM36-2", "DM36-3", "DM37-2", "DM37-3", "DM38-2", "DM38-3", "DM39-2"];
    for(var i = 0; i < data.length; i += 3) {
        var tbodyRow = document.createElement("tr");
        for(var j = i; j < i + 3; j++) {
            var tbodyCell = document.createElement("td");
            tbodyCell.textContent = data[j];
            tbodyRow.appendChild(tbodyCell);
        }
        tbody.appendChild(tbodyRow);
    }

    // 将 thead 和 tbody 添加到表格中
    table.appendChild(thead);
    table.appendChild(tbody);

    // 将表格添加到页面中的容器元素
    var tableContainer = document.getElementById("table-container");
    tableContainer.appendChild(table);
}

        //     function loadFile() {
        //     // 获取文件对象
        //     const file = document.getElementById('input-file').files[0];
        //     const reader = new FileReader();
        //     reader.readAsBinaryString(file);
        //     reader.onloadend = function() {
        //         localStorage.setItem('uploadedFile', reader.result);
        //         console.log('File was saved to cache successfully!');
        //     }
        // }
        
    let markerAddin;
        
async function main() {


    const applicationOptions = {
        getAccessToken: getAccessToken,
        refreshAccessToken: getAccessToken,
        serviceConfig: {
            origin: 'https://api.cloud.pkpm.cn',
            apiContextPath: '/bimserver/viewing/v3',
        },
    };
    const viewer3dConfig = {
        addinConfigs: [
            {
                id: 'OBVAddins.Marker',
                noButton: false,
            },
        ],
    };
    let urn = 'urn:bimbox.object:1NnyKhLmCpG/luomashi_test_biaozhu_p3d';
    // let urn_xlsx = 'urn:bimbox.object:test_bucket/all_dtata_xlsx';//将xlsx文件加载下来
    // let urn = 'urn:bimbox.object:viewing_bucket/rvt-model';
    // 实例化 Builder，用于模型加载
    const builder = new OBV.Api.ObvBuilder();
    // 创建 Application 对象
    const application = await builder.buildApplication(applicationOptions);
    // 创建 document 管理视图，加载完成后可以调用接口
    const obvDocument = await builder.loadDocument(application, urn);
    // const XLSX = await builder.loadDocument(application,urn_xlsx);
    // console.log('xlsx',XLSX)
    // 创建 viewer 容器, 创建API
    const obvApi = await builder.buildViewer3d(application, document.getElementById('viewer'), viewer3dConfig);
    console.log(obvApi)
    // 获取三维模型视图
    const viewer3dItems = obvDocument.get3dGeometryItems();
    // 加载模型
    builder.load3dModels(obvApi, {
        obvDocument: obvDocument,
        viewer3dItem: viewer3dItems[0],
    });
    // 聚焦到模型
    obvApi.addEventListener(OBV.ViewerEventTypes.V3dGeometryLoadedEvent, () => {
        obvApi.fitToView();
        
    })


    /*
        直接监视viwer的动态信息 
        1 如果点击模型中的构建 
            则获取构建id 并显示marker和曲线图
        2 如果点击信息为空
            则执行clearMarkers移除标记和曲线图
    */
    var dbId = 1;//初始化dbid为1
    var onclick_num = 0;//点击按钮的次数

    var Viewer_click_info = {};//定义模型点击事件
    // 获取所有的<td>元素
    var tdElements = document.querySelectorAll("td");

// 添加点击事件监听器
tdElements.forEach(function(td) {
    td.addEventListener("click", function() {
        onclick_num ++;
        // alert("您点击了单元格: " + this.textContent);
        // console.log("您点击了单元格: " + this.textContent)
        DM_name = this.textContent;
        //显示 marker和对应曲线图
        console.log(onclick_num);
        console.log(DM_name);
        // markerAddin.clearMarkers();
        make_marker(onclick_num,DM_name);
    });
});
    obvApi.addEventListener(
        OBV.ViewerEventTypes.V3dViewer3dStateChangeEvent,
        (event) => {
            // 控制台输出监听事件的返回值，调用`V3dViewer3dStateChangeEvent`监听返回到的是模型当前的状态信息
            // event.state.nodeIdArray
            console.log('event',event)
            if (event.state.type === 'selection'){
                // console.log('get it')
                const get_infortmation = event.state.nodeIdArray;
                Viewer_click_info = get_infortmation;
                if (get_infortmation.length !== 0 ){
                    //如果数组不为空则 显示marker和曲线
                    onclick_num ++;

                    console.log('显示dbid',get_infortmation[0].dbId);
                    //获取dbID
                    dbId = get_infortmation[0].dbId;
                    // let previousID = null;
                    // if (dbId !== previousID && onclick_num !== 1){
                    //     //当前id与上次不一样 且不是第一次点击
                    //     console.log('当前id与上次不一样');
                    //     previousID = dbId;
                    // }
                    //显示 marker和对应曲线图
                    console.log(onclick_num);
                    // markerAddin.clearMarkers();
                    // 先不显示
                    // make_marker(onclick_num,DM_name);
                                     

                }else{
                    console.log('删除标记点和曲线');
                    markerAddin.clearMarkers();
                    // console.log('markerAddin',markerAddin)
                }
            }
        }
    );

// 这里是移除标记
document.getElementById('clearMarkerComponentOne').onclick = function() {
    clear_marker();
};
//移除标记的函数clear_marker
function clear_marker(){
    markerAddin.clearMarkers();
    // 选中模型中得对应构件
    obvApi.clearSelection();
};

//显示marker 的函数
function make_marker(onclick_num,DM_name){

// 创建一个图表容器
// if (!document.getElementById('my-chart-container')) {
    if (!document.getElementById('chart-container')) {
        console.log('no chart-container');
        const myChartDomCon = document.createElement('div');
        // myChartDomCon.setAttribute('id', 'my-chart-container');
        myChartDomCon.setAttribute('id', 'chart-container');
        const myChartDom = document.createElement('div');
        myChartDomCon.appendChild(myChartDom);
        myChartDom.id = 'chart';
        myChartDom.style.width = '400px';
        myChartDom.style.height = '250px';
        // myChartDom.style.margin = '0 auto';
        document.getElementById('viewer').appendChild(myChartDomCon);
    };
    // 获取插件
    const addinManager = obvApi.getAddinManager();
    markerAddin = addinManager.getAddin(viewer3dConfig.addinConfigs[0].id);
    console.log(markerAddin)
    if (!markerAddin) {
        // 插件没有加载过，需要加载到平台中
        addinManager.loadAddin(viewer3dConfig.addinConfigs[0].id);
        markerAddin = addinManager.getAddin(viewer3dConfig.addinConfigs[0].id);
    };

    // 将data跑算法 再绘图
    // 直接传 DM_name
    $.ajax({
          url: 'http://127.0.0.1:5000/data',
          type: 'POST',
          contentType: 'application/json',
          data: JSON.stringify({ 'DM_name': DM_name}),
          success: function(response) {
            $('#result').text(response.processed_data);
            // alert('success')
            console.log(response.processed_data);
            maker_function(dbId=response.dbid,obvApi,markerAddin,onclick_num);
            drawChart(response.processed_data,onclick_num);
          }
        });


    


    // 选中模型中得对应构件
    // drawChart_function(onclick_num,dbId);
};

function maker_function(dbId,obvApi,markerAddin,onclick_num){
    // 获取参数,可以增加观测点位，包括构件ID与位置
    const componentOneNodeId = [{ dbId, modelId: 1 }];
    // const componentOneNodeId = 639;0
    // 创建 viewer 容器, 创建API
    // const obvApi = builder.buildViewer3d(application, document.getElementById('viewer'), viewer3dConfig);
    const bbox = obvApi.getObjectsBounds(componentOneNodeId);
    // const bbox_2 = obvApi.getObjectsBounds(componentOneNodeId);
    // const tag = document.getElementById('componentOneMarkerTag').value;
    const message = document.getElementById('chart-container').innerHTML;
    const externalId =1;
    // const externalId_2 = 639;
    const offsetX = 40;
    // const offsetX_2 = 40
    const offsetY = 40;
    // const offsetY_2 = 40;
    const customizedStyles = {
        annotationBackgroundColor: 'rgba(1, 1, 1, 0.8)',
    };
    // 标记点的形状和图标
    markerAddin.createTextSymbolMarker(
        bbox.center(new THREE.Vector3()),
        'i',
        message,
        message,
        externalId,
        offsetX,
        offsetY,
        customizedStyles,
    );

    // 这里所有的div才建立完成
    var element = $(`div.marker-annotation#${onclick_num}`);//获取id=1 class=marker-annotation的div信息
    // console.log('element',element)
    if (element.length === 0){
        console.log(element.prevObject[0].all.chart[0]);
        var chlid_div = element.prevObject[0].all.chart[0];
    }else{
        var chlid_div = element[0].getElementsByTagName("div")[1];
    }
    console.log('child_div',chlid_div)
    
    chlid_div.id = `chart${onclick_num}`
    // var child = element.getElementsByTagName("div");

    // console.log('div.marker-annotation 的information',element[0].getElementsByTagName("div")[1]);
    console.log('div改id后',chlid_div);
}

};


//主函数
main();

// 访问的令牌 getAccessToken 和 令牌有效期 expiresIn 
function getAccessToken(callBack) {
callBack('eyJhbGciOiJSUzI1NiJ9.eyJzY29wZSI6WyJvYnY6cmVhZCJdLCJleHAiOjE3Mzk1NTAzNDQsImNsaWVudF9pZCI6IjQwZGVwSjRJRHByTDNLTU9SdzRINlhuNSIsImp0aSI6Ijc1YzZmODUwLWVkNTctNDc3Yy04NTVjLWI1NTEzMDk5YzJmNSJ9.VIyN07B6i77UV9axBPuK6_5MVROR-GCssYdNsZ7JHYUZpcXh8jH5nF6Wj163tGbo0RR_-gT409Wx_vx1zRbHQ34VRRTvMmdgpiOmFRiw9iZjgUgvKE-sB2eag1Xjtu9M5f4j67PW54AGKqPRbMvaDQ5ZSHYVJQW1veL-De7IaHQZqoell1M1nqQraycekaWteqafryOmSfFI02wzSCffQHzIdgm_ioKGlbLpzrfA65kHVW5HmonKN4qCTwjpdC7IMGP4XeCjUOtAEQDYHmuYKr_hB9zP8-88WdwRi-irZYtseNMMIbxLU1151I5YVfgpi7A6fvuEnClVHAs3YtX7Eg', 36000)
}


// // 绘制折线图 需要传入点击次数onclick_num是为了对应marker和data
// function drawChart_function(onclick_num,dbId) {
//     console.log('active!');
//     //获取flask上传的json数据
//     var json = JSON.parse('{{ data|safe }}');
//     choose_data(json,dbId,onclick_num);

                   
// }
function drawChart(data,onclick_num) {
    // 定义Highcharts配置项
    const options = {
        chart: {
            type: 'line'
        },
        title: {
            text: '竖向位移累计曲线'
        },
        xAxis: {
            title: {
                text: '期数'
            },
            categories: []
        },
        yAxis: {
            title: {
                text: '竖向位移（mm）'
            }
        },
        series: []
    };
    // 遍历数据，添加类别和数据系列
    for (let i = 0; i < data.length; i++) {
        const item = data[i];
        options.xAxis.categories.push(item['日期']);
        for (const key in item) {
            if (key !== '日期') {
                let found = false;
                for (let j = 0; j < options.series.length; j++) {
                    if (options.series[j].name === key) {
                        options.series[j].data.push(parseFloat(item[key]));
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    options.series.push({
                        name: key,
                        data: [parseFloat(item[key])]
                    });
                }
            }
        }
    }
    // 渲染图表
    Highcharts.chart(`chart${onclick_num}`, options);
}
 
function choose_data(jsonData,dbId,onclick_num){
    // 将jsonData 中的key获取出来
    const titles = [];

    for (const key in jsonData[0]) {
        if (key !== '__rowNum__') {
            titles.push(key);
        }
    }
    // 定义指定的id列表 1243
    var data_ID = {'DM1-2':1248,'DM1-3':1249,'DM2-2':1254,'DM36-3':1244,'DM37-2':1243,'DM37-3':1242,'DM38-2':1243,'DM38-3':1348,'DM39-2':1349,'DM39-3':1350,
              'DM40-2':1351,'DM41-3':1352,'DM42-2':1353,'DM42-3':1354,'DM43-2':1355,'DM43-3':1356,'DM44-2':1357,'DM44-3':1358,'DM45-2':1359,'DM45-3':1360,
              'DM46-2':1361,'DM46-3':1362,'DM47-2':1363,'DM47-3':1364,'DM48-2':1365,'DM48-3':1366,'DM49-2':1367,'DM49-3':1368,'DM50-2':1369,'DM50-3':1370,
              'DM51-2':1400,'DM51-3':1401,'DM52-2':1402,'DM52-3':1403,'DM53-2':1405,'DM53-3':1325,'DM54-2':1326,'DM54-3':1327,'DM55-2':1322,'DM55-3':1323,
              'DM56-2':1315,'DM56-3':1314,'DM57-2':1316,'DM57-3':1317,'DM58-2':1318,'DM58-3':1318,'DM59-2':1319,'DM59-3':1320,'DM60-2':1321,'DM60-3':200,
              'DM61-2':67,'DM61-3':2,'DM62-2':53,'DM62-3':54,'DM63-2':55,'DM63-3':56,'DM64-2':57,'DM64-3':58,'DM65-2':59,'DM65-3':60,
    };

    console.log(titles);
    const findKey = Object.entries(data_ID).find(([key, value]) => value === dbId);
        if (findKey) {
            var [titles_key, value] = findKey;
            console.log('titles_key',titles_key); // 输出titlekey

        } else {
            console.log('未找到对应的键');
            var titles_key = titles[1];
        }

    // 只获取title中的其中一个key的数据
    // console.log(jsonData)
    const groupedData = {
        A: [],
    };

    // 分组数据
    for (let i = 0; i < jsonData.length; i++) {
        const groupA = {};
        const rowData = jsonData[i];

        for (const key in rowData) {
            if (key.startsWith(titles_key)) {//只需要修改title中的num_id即可
                groupA[key] = rowData[key];
            } 
        }

        groupedData.A.push(groupA);
    }

    data = groupedData.A;
        // $.ajax({
        //   url: 'http://127.0.0.1:5001/data',
        //   type: 'POST',
        //   contentType: 'application/json',
        //   data: JSON.stringify({ 'input_data': data ,'data_name':titles_key}),
        //   success: function(response) {
        //     $('#result').text(response.processed_data);
        //     // alert('success')
        //     console.log(response.processed_data);
        //     drawChart(response.processed_data,onclick_num)
        //   }
        // });
    // console.log(groupedData.A);
    return [data,titles_key];
}
            </script>
        </body>
    </html>
